package top.jnaw.jee.utils.nim;

import com.alibaba.fastjson.JSONObject;
import java.security.MessageDigest;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import top.jnaw.jee.platform.Consts;
import top.jnaw.jee.utils.Https;
import top.jnaw.jee.utils.Strings;

/**
 * Created by tudou on 17/11/21 下午4:18.
 */
public class Utils {

  private static final char[] HEX_DIGITS = {'0', '1', '2', '3', '4', '5',
      '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};

  public static Map<String, String> getHeaders(String appKey,
      String appSecret) {
    final String nonce = String.valueOf((int) (Math.random() * 999999));
    final String curTime = String.valueOf((new Date()).getTime() / 1000L);
    final String checkSum = getCheckSum(appSecret, nonce, curTime);

    Map<String, String> headers = new HashMap<>();
    headers.put("AppKey", appKey);
    headers.put("Nonce", nonce);
    headers.put("CurTime", curTime);
    headers.put("CheckSum", checkSum);
    headers.put("Content-Type",
        "application/x-www-form-urlencoded;charset=utf-8");

    return headers;
  }

  // 计算并获取CheckSum
  public static String getCheckSum(String appSecret, String nonce,
      String curTime) {
    return encode("sha1", appSecret + nonce + curTime);
  }

  // 计算并获取md5值
  public static String md5(String requestBody) {
    return encode("md5", requestBody);
  }

  private static String encode(String algorithm, String value) {
    if (value == null) {
      return null;
    }
    try {
      MessageDigest messageDigest
          = MessageDigest.getInstance(algorithm);
      messageDigest.update(value.getBytes());
      return getFormattedText(messageDigest.digest());
    } catch (Exception e) {
      throw new RuntimeException(e);
    }
  }

  private static String getFormattedText(byte[] bytes) {
    int len = bytes.length;
    StringBuilder buf = new StringBuilder(len * 2);
    for (int j = 0; j < len; j++) {
      buf.append(HEX_DIGITS[(bytes[j] >> 4) & 0x0f]);
      buf.append(HEX_DIGITS[bytes[j] & 0x0f]);
    }
    return buf.toString();
  }

  protected static JSONObject requestSMS(String url, Map<String, String> req) {
    Map<String, String> header = getHeaders(Consts.NIM_SMS_KEY,
        Consts.NIM_SMS_SECRET);
    String res = Https.post(url, header, req);
    return Strings.toJSONObject(res);
  }

  protected static JSONObject request(String url, Map<String, String> req) {
    Map<String, String> header = getHeaders(Consts.NIM_KEY, Consts.NIM_SECRET);
    String res = Https.post(url, header, req);
    return Strings.toJSONObject(res);
  }
}
